package com.jhd.fuzhou.view.receipt;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.bigkoo.pickerview.TimePickerView;
import com.google.gson.Gson;
import com.jhd.fuzhou.R;
import com.jhd.fuzhou.service.ReceiveService;
import com.jhd.fuzhou.service.SupervisionService;
import com.jhd.fuzhou.util.EditTextView;
import com.jhd.fuzhou.util.UtilHelper;
import com.jhd.fuzhou.view.login.BaseActivity;
import com.jhd.fuzhou.vo.CheckValue;
import com.jhd.fuzhou.vo.GlobalDictionaryVo;
import com.jhd.fuzhou.vo.JsonForResult;
import com.jhd.fuzhou.vo.ReceiveReportVo;
import com.jhd.fuzhou.vo.SearchUnit;

import net.zigin.commons.util.StringUtil;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

import static com.jhd.fuzhou.util.TimeUtil.getTime2;

public class ReceiptManagementActivity extends BaseActivity {
    @BindView(R.id.rv_receipt)RecyclerView rv_receipt;
    private String[] statusList=new String[]{"已分发","已归档"};
    private ProgressDialog _dialog;
    private Context context=this;
    private LinearLayoutManager layoutManager;
    @BindView(R.id.tv_loading)TextView tv_loading;
    private SearchUnit searchUnit;
    private List<ReceiveReportVo> receiveReportVoList=new ArrayList<>();
    private ReceiveReportAdapter receiveReportAdapter;
    private AlertDialog _alertDialog;
    private RecyclerView rv_dialog_type,rv_dialog_status;
    private TextView tv_startDate,tv_endDate;
    private String reportStatus,fileType,searchTitle,startDate,endDate;
    private CheckValue checkValue=null;private List<GlobalDictionaryVo> globalDictionaryVos;
    private EditText et_search_dialog;

    @Override
    protected void loadViewLayout() {
        setContentView(R.layout.activity_receipt_management);
    }

    @Override
    protected void processLogic() {
        onBack();
        refresh();
        getCheckValue();
        layoutManager = new LinearLayoutManager(context);
        rv_receipt.setLayoutManager(layoutManager);
    }

    private void refresh(){
        receiveReportVoList.clear();
        _dialog = new ProgressDialog(context);
        searchUnit=new SearchUnit();
        searchUnit.setPageIndex(1);
        searchUnit.setPageNum(1);//默认只有一页
        searchUnit.setUsername(application.getUserName());//username不变
        searchUnit.setStatus("1");//状态一直是"1"
        getReceiveReportList();
        rv_receipt.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                int lastCompletelyVisibleItemPosition = layoutManager.findLastCompletelyVisibleItemPosition();
                if(lastCompletelyVisibleItemPosition==layoutManager.getItemCount()-1){
                    tv_loading.setVisibility(View.VISIBLE);
                    searchUnit.setPageIndex(searchUnit.getPageIndex()+1);
                    if(searchUnit.getPageIndex()<=searchUnit.getPageNum()){
                        tv_loading.setText(getString(R.string.loading));
                        getReceiveReportList();
                    }else{
                        tv_loading.setText(getString(R.string.arrival_bottom));
                    }
                }else{
                    tv_loading.setVisibility(View.GONE);//没到底部，隐藏
                }
            }
        });
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        refresh();
    }

    @OnClick({R.id.lin_select})
    public void onClick(View v){
        switch (v.getId()){
            case R.id.lin_select:
                dialogShow();
                break;
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    private void getCheckValue(){
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.UC());//URL的头
        SupervisionService vs = retrofit.create(SupervisionService.class);
        JSONArray jsonArray=new JSONArray();
        jsonArray.add("文件管理类型");
        Map<String, Object> params = new LinkedHashMap<String, Object>();
        params.put("nameList",jsonArray);
        RequestBody requestBody = RequestBody.create(MediaType.parse("Content-Type, application/json"),
                JSON.toJSONString(params));
        Call<JsonForResult> jsonForResultCall = vs.getValueList(application.getAccessToken(), requestBody);
        jsonForResultCall.enqueue(new Callback<JsonForResult>() {
            @Override
            public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                try {
                    JsonForResult jsonForResult = response.body();
                    if (jsonForResult != null && jsonForResult.isSuccess()) {
                        //请求授权信息
                        if(jsonForResult.getData()!=null){
                            checkValue= JSON.parseArray(jsonForResult.getData().toString(), CheckValue.class).get(0);
                            globalDictionaryVos=checkValue.getGlobalDictionaryVoMap();
                        }
                    }
                } catch (Exception e) {
                    UtilHelper.alertMsg(context, "错误", e.getMessage());
                }
            }
            @Override
            public void onFailure(Call<JsonForResult> call, Throwable t) {
                String msg = "获取文件类型失败!";
                UtilHelper.alertMsg(context, "错误", msg);
            }
        });
    }

    private void getReceiveReportList() {
        if(!_dialog.isShowing()){
            _dialog.setMessage("正在获取收文列表,请稍等...");
            _dialog.show();
        }
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.API());//URL的头
        ReceiveService vs = retrofit.create(ReceiveService.class);
        Map<String, Object> params = new LinkedHashMap<String, Object>();
        params.put("pageIndex", searchUnit.getPageIndex());
        params.put("pageSize", 20);
        params.put("status", "1");
        if(!StringUtil.isNullOrEmpty(application.getUserName()))params.put("userName", application.getUserName());
        if(!StringUtil.isNullOrEmpty(searchUnit.getReportStatus()))params.put("reportStatus", searchUnit.getReportStatus());
        if(!StringUtil.isNullOrEmpty(searchUnit.getReportTitle()))params.put("reportTitle", searchUnit.getReportTitle());
        if(!StringUtil.isNullOrEmpty(searchUnit.getFileType()))params.put("fileType", searchUnit.getFileType());
        if(!StringUtil.isNullOrEmpty(searchUnit.getStartDate()))params.put("startDate", searchUnit.getStartDate());
        if(!StringUtil.isNullOrEmpty(searchUnit.getEndDate()))params.put("endDate", searchUnit.getEndDate());
        Call<JsonForResult> jsonForResultCall = vs.getReceiveReportListByApp(application.getAccessToken(), params);//调用接口获取json返回
        jsonForResultCall.enqueue(new Callback<JsonForResult>() {
            @Override
            public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                if(_dialog != null)_dialog.cancel();
                try {
                    JsonForResult jsonForResult = (JsonForResult) response.body();
                    if (jsonForResult != null && jsonForResult.isSuccess()) {
                        if (jsonForResult.getData() != null) {
                            List<ReceiveReportVo> receiveReportVos = JSON.parseArray(jsonForResult.getData().toString(), ReceiveReportVo.class);
                            for (ReceiveReportVo receiveReportVo : receiveReportVos) {
                                receiveReportVoList.add(receiveReportVo);
                            }
                            if (searchUnit.getPageIndex() == 1) {
                                receiveReportAdapter = new ReceiveReportAdapter();
                                rv_receipt.setAdapter(receiveReportAdapter);
                            } else {
                                tv_loading.setVisibility(View.GONE);
                                receiveReportAdapter.notifyDataSetChanged();
                            }
                            searchUnit.setPageNum(jsonForResult.getTotal()/20+1);
                        } else {
                            receiveReportAdapter = new ReceiveReportAdapter();
                            rv_receipt.setAdapter(receiveReportAdapter);
                            tv_loading.setText(context.getString(R.string.arrival_bottom));
                        }
                    } else {
                        UtilHelper.alertMsg(context, "错误", jsonForResult.getMessage());
                    }
                } catch (Exception e) {
                    if(_dialog != null)_dialog.cancel();
//                    CustomToast.showText(context,e.getLocalizedMessage(),3000,0,0).show();
                }
            }

            @Override
            public void onFailure(Call<JsonForResult> call, Throwable t) {
                if(_dialog != null)_dialog.cancel();
                String msg = "网络异常!";
                if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg;
                UtilHelper.alertMsg(context, "错误", msg);
            }
        });
    }
    private class ReceiveReportAdapter extends RecyclerView.Adapter<ReceiveReportAdapter.ViewHolder> {
        @Override
        public ReceiveReportAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_receipt, parent, false);
            ReceiveReportAdapter.ViewHolder viewHolder = new ReceiveReportAdapter.ViewHolder(itemView);
            return viewHolder;
        }

        @Override
        public void onBindViewHolder(@NonNull ReceiveReportAdapter.ViewHolder holder, int position) {
            holder.linearLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent=new Intent(context,ReceiptDetailActivity.class);
                    Gson gson = new Gson();
                    intent.putExtra("data", gson.toJson(receiveReportVoList.get(position)));
                    startActivity(intent);
                }
            });
            holder.tv_status.setText(StringUtil.isNullOrEmpty(receiveReportVoList.get(position).getReportStatus())?"":receiveReportVoList.get(position).getReportStatus());
            holder.tv_task_type.setText(StringUtil.isNullOrEmpty(receiveReportVoList.get(position).getFileType())?"":receiveReportVoList.get(position).getFileType());
            holder.tv_dept.setText(StringUtil.isNullOrEmpty(receiveReportVoList.get(position).getDistributeUnitName())?"":receiveReportVoList.get(position).getDistributeUnitName());
            holder.tv_taskName.setText(StringUtil.isNullOrEmpty(receiveReportVoList.get(position).getReportTitle())?"":receiveReportVoList.get(position).getReportTitle());
            if(receiveReportVoList.get(position).getLookUpAndComment()){
                if("1".equals(receiveReportVoList.get(position).getHasRead())){
                    holder.tv_status_type.setText("已阅文");
                }else{
                    holder.tv_status_type.setText("待阅文");
                }
            }else{
                holder.tv_status_type.setText("待审核");
            }
            if(!StringUtil.isNullOrEmpty(receiveReportVoList.get(position).getDistributeDate()))holder.tv_date.setText(receiveReportVoList.get(position).getDistributeDate().substring(0,11));
        }

        @Override
        public int getItemCount() {
            return receiveReportVoList.size();
        }

        class ViewHolder extends RecyclerView.ViewHolder {
            TextView tv_date,tv_taskName,tv_dept,tv_task_type,tv_status,tv_status_type;
            LinearLayout linearLayout;
            public ViewHolder(View itemView) {
                super(itemView);
                this.tv_date = itemView.findViewById(R.id.tv_date);
                this.tv_taskName = itemView.findViewById(R.id.tv_taskName);
                this.tv_dept = itemView.findViewById(R.id.tv_dept);
                this.tv_task_type = itemView.findViewById(R.id.tv_task_type);
                this.tv_status = itemView.findViewById(R.id.tv_status);
                this.linearLayout = itemView.findViewById(R.id.linearLayout);
                this.tv_status_type = itemView.findViewById(R.id.tv_status_type);
            }
        }
    }
    public void dialogShow() {
        LayoutInflater mLayoutInflater = LayoutInflater.from(this);
        View view = mLayoutInflater.inflate(R.layout.dialog_receive, null);
        final AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context, R.style.ActionSheetDialogStyle);
        alertBuilder.setView(view);
        _alertDialog = alertBuilder.create();
        //获取当前Activity所在的窗体
        Window window = _alertDialog.getWindow();
        window.setGravity(Gravity.BOTTOM);
        _alertDialog.show();
        et_search_dialog = (EditText) view.findViewById(R.id.et_search);
        if(searchTitle!=null)et_search_dialog.setText(searchTitle);
        ImageView iv_cancel_dialog = (ImageView) view.findViewById(R.id.iv_cancel);
        ImageView iv_dismiss = (ImageView) view.findViewById(R.id.iv_dismiss);
        Button btn_reset = (Button) view.findViewById(R.id.btn_reset);
        Button btn_confirm = (Button) view.findViewById(R.id.btn_confirm);
        rv_dialog_type = (RecyclerView) view.findViewById(R.id.rv_type);
        //rv_dialog_status = (RecyclerView) view.findViewById(R.id.rv_status);
        tv_startDate=(TextView)view.findViewById(R.id.tv_startDate);
        tv_endDate=(TextView)view.findViewById(R.id.tv_endDate);
        if(startDate!=null)tv_startDate.setText(startDate);
        if(endDate!=null)tv_endDate.setText(endDate);
        tv_startDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getTimeDialog(tv_startDate);
            }
        });
        tv_endDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getTimeDialog(tv_endDate);
            }
        });
        btn_reset.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setTypeButton(rv_dialog_type);//setStatusButton(rv_dialog_status);
                reportStatus=null;fileType=null;et_search_dialog.setText("");
                tv_startDate.setText("开始日期");
                tv_endDate.setText("结束日期");
            }
        });
        btn_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                _alertDialog.dismiss();
                searchUnit.setPageIndex(1);
                searchUnit.setReportTitle(StringUtil.isNullOrEmpty(et_search_dialog.getText().toString().trim())?null:et_search_dialog.getText().toString());
                searchUnit.setReportStatus(reportStatus);
                searchUnit.setFileType(fileType);
                searchUnit.setStartDate(("开始日期".equals(tv_startDate.getText().toString()))?null:tv_startDate.getText().toString()+" 00:00:00");
                searchUnit.setEndDate(("结束日期".equals(tv_endDate.getText().toString()))?null:tv_endDate.getText().toString()+" 23:59:59");
                searchUnit.setPageNum(1);
                receiveReportVoList.clear();
                searchTitle=et_search_dialog.getText().toString().trim();
                if(!"开始日期".equals(tv_startDate.getText().toString()))startDate=tv_startDate.getText().toString();
                if(!"结束日期".equals(tv_endDate.getText().toString()))endDate=tv_endDate.getText().toString();
                getReceiveReportList();
            }
        });
        iv_dismiss.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                _alertDialog.dismiss();
            }
        });
        iv_cancel_dialog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                et_search_dialog.setText("");
                iv_cancel_dialog.setVisibility(View.GONE);
            }
        });
        et_search_dialog.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) { }
            @Override
            public void afterTextChanged(Editable s) {
                if(!s.toString().equals("")){
                    iv_cancel_dialog.setVisibility(View.VISIBLE);
                }else{
                    iv_cancel_dialog.setVisibility(View.GONE);
                }
            }
        });
        setTypeButton(rv_dialog_type);//setStatusButton(rv_dialog_status);
        WindowManager.LayoutParams params = window.getAttributes() ;
        params.width =(int) (getWindowManager().getDefaultDisplay().getWidth());                     //使用这种方式更改了dialog的框宽
        window.setAttributes(params);
    }
    public void getTimeDialog(TextView view) {
        TimePickerView timePickerView = new TimePickerView.Builder(context, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                String start = getTime2(date);
                view.setText(start);
                EditTextView.TextViewChange(view,context);
            }
        }).setType(new boolean[]{true, true, true, false, false, false})
                .isDialog(true)
                .setCancelColor(context.getResources().getColor(R.color.colorCyan300))
                .setSubmitColor(context.getResources().getColor(R.color.colorCyan500)).build();
        //注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
        timePickerView.setDate(Calendar.getInstance());
        timePickerView.show();
    }
    /*设置文件类型的选择*/
    public void setTypeButton(RecyclerView recyclerView){
        GridLayoutManager layoutManage = new GridLayoutManager(context, 2);
        recyclerView.setLayoutManager(layoutManage);
        if(globalDictionaryVos!=null){
            TypeAdapter recyclerAdapter=new TypeAdapter(globalDictionaryVos);
            recyclerView.setAdapter(recyclerAdapter);
        }
    }
    /*设置类型的选择*/
    public void setStatusButton(RecyclerView recyclerView){
        GridLayoutManager layoutManage = new GridLayoutManager(context, 2);
        recyclerView.setLayoutManager(layoutManage);
        StatusAdapter recyclerAdapter=new StatusAdapter(statusList);
        recyclerView.setAdapter(recyclerAdapter);
    }
    public class StatusAdapter extends RecyclerView.Adapter<StatusAdapter.ViewHolder> {
        private String[] statusList;
        private int checkPosition=-1;//默认全不选

        public StatusAdapter(String[] statusList) {
            this.statusList = statusList;
        }

        @NonNull
        @Override
        public StatusAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_radio, parent, false);
            StatusAdapter.ViewHolder viewHolder = new StatusAdapter.ViewHolder(itemView);
            return viewHolder;
        }

        @Override
        public void onBindViewHolder(@NonNull StatusAdapter.ViewHolder holder, int position) {
            holder.rb_radio.setText(statusList[position]);
            if(reportStatus!=null&&reportStatus.equals(statusList[position]))checkPosition=position;
            holder.rb_radio.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    checkPosition=position;
                    reportStatus=statusList[checkPosition];
                    notifyDataSetChanged();
                }
            });
            if(position==checkPosition){
                holder.rb_radio.setChecked(true);
            }else{
                holder.rb_radio.setChecked(false);
            }
        }

        @Override
        public int getItemCount() {
            return statusList.length;
        }

        class ViewHolder extends RecyclerView.ViewHolder {
            RadioButton rb_radio;
            public ViewHolder(View itemView) {
                super(itemView);
                this.rb_radio = itemView.findViewById(R.id.rb_radio);
            }
        }
    }
    public class TypeAdapter extends RecyclerView.Adapter<TypeAdapter.ViewHolder> {
        private List<GlobalDictionaryVo> globalDictionaryVos;
        private int checkPosition=-1;//默认全不选

        public TypeAdapter(List<GlobalDictionaryVo> globalDictionaryVos) {
            this.globalDictionaryVos = globalDictionaryVos;
        }

        @NonNull
        @Override
        public TypeAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_radio, parent, false);
            TypeAdapter.ViewHolder viewHolder = new TypeAdapter.ViewHolder(itemView);
            return viewHolder;
        }

        @Override
        public void onBindViewHolder(@NonNull TypeAdapter.ViewHolder holder, int position) {
            holder.rb_radio.setText(globalDictionaryVos.get(position).getValue());
            if(fileType!=null&&fileType.equals(globalDictionaryVos.get(position).getValue()))checkPosition=position;
            holder.rb_radio.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    checkPosition=position;
                    fileType=globalDictionaryVos.get(position).getValue();
                    notifyDataSetChanged();
                }
            });
            if(position==checkPosition){
                holder.rb_radio.setChecked(true);
            }else{
                holder.rb_radio.setChecked(false);
            }
        }

        @Override
        public int getItemCount() {
            return globalDictionaryVos.size();
        }

        class ViewHolder extends RecyclerView.ViewHolder {
            RadioButton rb_radio;
            public ViewHolder(View itemView) {
                super(itemView);
                this.rb_radio = itemView.findViewById(R.id.rb_radio);
            }
        }
    }

}